<?php

// Env::Ins()->config('DEBUG');
class Env {
    private $_apcConfigRuntime = null;
    
    
    private $_configPath = '';

    private $_configFile = '';

    private $_apcConfig = null;

    private static $_instance = null;

    static public function IsRuntime() {
        return ( defined('RUNTIME_MODE') || RUNTIME_MODE );
    }
    
    static public function Ins() {
        if ( !isset( self::$_instance ) ) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    private function __construct() {
        $this->_configFile = APP_NAME . '.config';
        $this->_configPath = '/etc/' . APP_NAME . '/' . $this->_configFile;


        if ( self::IsRuntime() ) {
            $this->_apcConfigRuntime = include CONFIG_PATH . 'Config.php';
        }
    }
    

    private function _readConfig( $isReread = false ) {
        $this->_apcConfig = apc_fetch( $this->_configFile );
        if ( !$this->_apcConfig ) {
            if ( is_file( $this->_configPath ) ) {
                $this->_apcConfig = parse_ini_file( $this->_configPath );
                if ( $this->_apcConfig ) {
                    apc_store( $this->_configFile, $this->_apcConfig );
                }
            }
            else {
                throw new \Exception( 'readConfig path is not exist! Path:' . $this->_configPath );
            }
        }
    }

    private function _returnBool( $key ) {
        return $this->config( $key ) ? true : false;
    }
    
    private function _returnInt( $key ) {
        return (int)$this->config( $key );
    }

    
    public function config( $key ) {
        $key = strtoupper($key);
        if ( !isset( $this->_apcConfig ) ) {
            $this->_readConfig();
        }

        if ( self::IsRuntime()  ) {
            $this->_apcConfig = array_merge($this->_apcConfig, $this->_apcConfigRuntime );
        }
    
        if ( is_array( $this->_apcConfig ) && array_key_exists( $key, $this->_apcConfig ) ) {
            return $this->_apcConfig["$key"];
        }
        else {
            return NULL;
        }
    }
    
    public function rereadConfig() {
        if ( is_file( $this->_configPath ) ) {
            $this->_apcConfig = parse_ini_file( $this->_configPath );
            if ( $this->_apcConfig ) {
                apc_store( $this->_configFile, $this->_apcConfig );
            }
        }
        else {
            throw new Exception( 'readConfig path is not exist! Path:' . $this->_configPath );
        }
    }

    public function isDevelop() {
        return $this->_returnBool( 'DEVELOP' );
    }


    public function isProfiler() {
        return $this->_returnBool( 'PROFILER' );
    }
    
    public function isMaintenance() {
        return $this->_returnBool( 'MAINTENANCE' );
    }
    
    public function version() {
        return $this->_returnInt( 'VERSION' );
    }
}